# encoding: utf-8
"""
@author: youfeng
@file: geetest_service.py
@time: 2018/6/18 下午8:07
"""
import requests

from common import util


class GeetestService(object):
    APPKEY = '752f1c68827376a986572feee086283e'

    def __init__(self, log=None):
        self.log = log

    def crack(self, gt, challenge, referer, model=3):

        if gt == '' or gt is None or challenge == '' or challenge is None:
            self.log.error("传入的极验参数异常: gt = {} challenge = {}".format(gt, challenge))
            return None

        url = 'http://jiyan.25531.com/api/create?gt={}&challenge={}&referer={}&model={}&appkey={}'.format(
            gt, challenge, referer, model, self.APPKEY)
        try:
            resp = requests.get(url, timeout=6)
            if resp is None:
                return None

            json_data = util.json_loads(resp.text)
            if json_data is None:
                self.log.error("破解返回数据解析异常: text = {}".format(resp.text))
                return None

            code = json_data.get("code")
            if code != 10000:
                self.log.error("破解失败: text = {}".format(resp.text))
                return None

            result_dict = json_data.get("data")
            if not isinstance(result_dict, dict):
                self.log.error("返回结果数据包异常: text = {}".format(resp.text))
                return None

            return result_dict.get("validate")
        except Exception as e:
            self.log.error("极验破解服务异常: ")
            self.log.exception(e)
        return None
